﻿using System;
using System.Threading.Tasks;
using OpenFileTransfer.Util.Extensions;
using OpenFileTransfer.Wpf.Tools;

namespace OpenFileTransfer.Wpf.Services
{
    // ReSharper disable IdentifierTypo
    public class SqliteService : ISqliteService
    {
        private readonly string _connectionString;
        private readonly ILogService _logService;

        public SqliteService(
            ILogService logService,
            IConfigService configService
        )
        {
            _logService = logService;
            _connectionString = Constants.SQLite.GetConnectionString(configService.AppDataDirectory);
        }

        public void PrepareSqlite()
        {
            Task.Run(async () => await PrepareSqliteAsync());
        }

        private async Task PrepareSqliteAsync()
        {
            var sqliteHelper = new SqliteHelper() { ConnectionString = _connectionString };
            await PrepareDatabaseAsync(sqliteHelper); //创建数据库
            await CreateTablesAsync(sqliteHelper); //创建表
        }

        private async Task PrepareDatabaseAsync(SqliteHelper sqliteHelper)
        {
            try
            {
                await sqliteHelper.PrepareDatabaseAsync();
            }
            catch (Exception e)
            {
                // ReSharper disable once StringLiteralTypo
                _logService.Error($@"SqliteService PrepareDatabaseAsync Exception: {e.GetFullMessage()}.");
            }
        }

        private async Task CreateTablesAsync(SqliteHelper sqliteHelper)
        {
            try
            {
                //设备信息表
                var sql = @"CREATE TABLE IF NOT EXISTS device_info(
	                            id VARCHAR(32) PRIMARY KEY,
	                            device_name VARCHAR(128) NOT NULL,
                                remark_name VARCHAR(128) NOT NULL,
                                is_self TINYINT NOT NULL,
                                create_time TEXT NOT NULL,
                                update_time TEXT NOT NULL,
                                remark TEXT
                            );";
                await sqliteHelper.ExecuteNonQueryAsync(sql);
            }
            catch (Exception e)
            {
                // ReSharper disable once StringLiteralTypo
                _logService.Error($@"SqliteService CreateTablesAsync Exception: {e.GetFullMessage()}.");
            }
        }
    }
}
